package com.spzx.order.service.impl;

import java.math.BigDecimal;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

import com.alibaba.nacos.common.utils.CollectionUtils;
import com.alibaba.nacos.common.utils.StringUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.spzx.cart.api.RemoteCartService;
import com.spzx.cart.api.domain.CartInfo;
import com.spzx.common.core.constant.SecurityConstants;
import com.spzx.common.core.context.SecurityContextHolder;
import com.spzx.common.core.domain.R;
import com.spzx.common.core.exception.ServiceException;
import com.spzx.common.rabbit.constant.MqConst;
import com.spzx.common.rabbit.service.RabbitService;
import com.spzx.order.domain.OrderForm;
import com.spzx.order.api.domain.OrderInfo;
import com.spzx.order.api.domain.OrderItem;
import com.spzx.order.domain.*;
import com.spzx.order.mapper.OrderItemMapper;
import com.spzx.order.mapper.OrderLogMapper;
import com.spzx.product.api.RemoteProductService;
import com.spzx.product.api.domain.ProductSku;
import com.spzx.product.api.domain.vo.SkuLockVo;
import com.spzx.product.api.domain.vo.SkuPrice;
import com.spzx.user.api.RemoteUserAddressService;
import com.spzx.user.api.domain.UserAddress;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;
import com.spzx.order.mapper.OrderInfoMapper;
import com.spzx.order.service.IOrderInfoService;
import org.springframework.transaction.annotation.Transactional;

/**
 * 订单Service业务层处理
 *
 * @author atguigu
 * @date 2024-09-01
 */
@Service
public class OrderInfoServiceImpl extends ServiceImpl<OrderInfoMapper, OrderInfo> implements IOrderInfoService
{
    @Autowired
    private OrderInfoMapper orderInfoMapper;

    @Autowired
    private OrderItemMapper orderItemMapper;
    
    @Autowired
    RemoteCartService remoteCartService;

    @Autowired
    RedisTemplate redisTemplate;

    @Autowired
    OrderLogMapper orderLogMapper;
    
    @Autowired
    RemoteProductService remoteProductService;

    @Autowired
    RemoteUserAddressService remoteUserAddressService;

    @Autowired
    RabbitService rabbitService;

    /**
     * 查询订单列表
     *
     * @param orderInfo 订单
     * @return 订单
     */
    @Override
    public List<OrderInfo> selectOrderInfoList(OrderInfo orderInfo)
    {
        return orderInfoMapper.selectOrderInfoList(orderInfo);
    }

    /**
     * 查询订单
     *
     * @param id 订单主键
     * @return 订单
     */
    @Override
    public OrderInfo selectOrderInfoById(Long id)
    {
        OrderInfo orderInfo = orderInfoMapper.selectById(id);
        List<OrderItem> orderItemList = orderItemMapper.selectList(new LambdaQueryWrapper<OrderItem>().eq(OrderItem::getOrderId, id));
        orderInfo.setOrderItemList(orderItemList);
        return orderInfo;
    }

    /**
     * 订单结算
     * @return TradeVo
     */
    @Override
    public TradeVo orderTradeData() {
        Long userId = SecurityContextHolder.getUserId();
        R<List<CartInfo>> cartCheckedListResult = remoteCartService.getCartCheckedList(userId, SecurityConstants.INNER);
        if (R.FAIL == cartCheckedListResult.getCode()){
            throw new ServiceException(cartCheckedListResult.getMsg());
        }
        List<CartInfo> cartInfoList = cartCheckedListResult.getData();
        if (CollectionUtils.isEmpty(cartInfoList)){
            throw new ServiceException("购物车无选中商品");
        }

        //准备List<OrderItem>
        List<OrderItem> orderItemList = cartInfoList.stream().map(cartInfo -> {
            OrderItem orderItem = new OrderItem();
            BeanUtils.copyProperties(cartInfo,orderItem);
            return orderItem;
        }).toList();

        //准备商品价格:BigDecimal类型
        BigDecimal totalAmout = new BigDecimal(0);
        for (OrderItem orderItem : orderItemList) {
            totalAmout = totalAmout.add(orderItem.getSkuPrice().multiply(new BigDecimal(orderItem.getSkuNum())));
        }

        //生成交易流水号
        String tradeNo = getTradeNo(userId);

        TradeVo tradeVo = new TradeVo();
        tradeVo.setOrderItemList(orderItemList);
        tradeVo.setTotalAmount(totalAmout);
        tradeVo.setTradeNo(tradeNo);
        
        return tradeVo;
    }

    private String getTradeNo(Long userId) {
        String tradeNo = UUID.randomUUID().toString().replaceAll("-", "");
        String tradeNoKey = "user:tradeNo:" + userId;
        redisTemplate.opsForValue().set(tradeNoKey,tradeNo,5, TimeUnit.MINUTES);
        return tradeNo;
    }

    /**
     * 下单
     * @param orderForm 下单提交的表单数据
     * @return 订单id
     */
    @Transactional
    @Override
    public Long submitOrder(OrderForm orderForm) {
        Long userId = SecurityContextHolder.getUserId();

        //1.验证用户是否通过浏览器回退进行重复提交订单
        String userTradeKey = "user:tradeNo:" + userId;
        String scriptText = "if redis.call(\"get\",KEYS[1]) == ARGV[1]\n" +
                "then\n" +
                "    return redis.call(\"del\",KEYS[1])\n" +
                "else\n" +
                "    return 0\n" +
                "end";
        DefaultRedisScript<Long> redisScript = new DefaultRedisScript<>();
        redisScript.setScriptText(scriptText);
        redisScript.setResultType(Long.class);
        Long execute = (Long) redisTemplate.execute(redisScript, Arrays.asList(userTradeKey), orderForm.getTradeNo());
        if (execute == 0){
            throw new ServiceException("请勿重复提交订单，请尝试重试");
        }

        //2.判断表单参数是否为空
        List<OrderItem> orderItemList = orderForm.getOrderItemList();
        if (CollectionUtils.isEmpty(orderItemList)){
            throw new ServiceException("请求不合法");
        }

        //3.校验价格变化
        List<Long> skuIdList = orderItemList.stream().map(OrderItem::getSkuId).toList();
        R<List<SkuPrice>> skuPriceListResult = remoteProductService.getSkuPriceList(skuIdList, SecurityConstants.INNER);
        if (R.FAIL == skuPriceListResult.getCode()){
            throw new ServiceException(skuPriceListResult.getMsg());
        }
        List<SkuPrice> skuPriceList = skuPriceListResult.getData();
        Map<Long, BigDecimal> SkuIdToSalePriceMap = skuPriceList.stream().collect(Collectors.toMap(SkuPrice::getSkuId, SkuPrice::getSalePrice));
        String priceCheckResult = "";
        for (OrderItem orderItem : orderItemList) {
            if (orderItem.getSkuPrice().compareTo(SkuIdToSalePriceMap.get(orderItem.getSkuId())) != 0){
                priceCheckResult += orderItem.getSkuName() +"价格变化了";
            }
        }
        if (StringUtils.isNotEmpty(priceCheckResult)){
            remoteCartService.updateCartPrice(userId, SecurityConstants.INNER);
            throw new ServiceException(priceCheckResult);
        }

        //4.校验库存锁定库存
        List<SkuLockVo> skuLockVoList = orderItemList.stream().map(orderItem -> {
            SkuLockVo skuLockVo = new SkuLockVo();
            skuLockVo.setSkuId(orderItem.getSkuId());
            skuLockVo.setSkuNum(orderItem.getSkuNum());
            return skuLockVo;
        }).toList();
        String checkAndLockResult = remoteProductService.checkAndLock(orderForm.getTradeNo(),
                skuLockVoList, SecurityConstants.INNER).getData();
        if (StringUtils.isNotEmpty(checkAndLockResult)){
            throw new ServiceException(checkAndLockResult);
        }

        //5.保存订单(订单表,订单项表,订单日志表)
        Long orderId = null;
        try {
            orderId = saveOrder(orderForm);
        } catch (Exception e) {
            e.printStackTrace();
            //下单失败解锁库存
            rabbitService.sendMsg(MqConst.EXCHANGE_PRODUCT, MqConst.ROUTING_UNLOCK, orderForm.getTradeNo());
            throw new ServiceException("下单失败");
        }

        //6.删除购物车选项
        remoteCartService.deleteCartCheckedList(userId, SecurityConstants.INNER);

        //7.发送延迟消息，取消订单
        rabbitService.sendMessage(MqConst.EXCHANGE_CANCEL_ORDER,
                MqConst.ROUTING_CANCEL_ORDER,
                orderId.toString(),
                MqConst.CANCEL_ORDER_DELAY_TIME);

        return orderId;
    }

    //保存订单(订单表,订单项表,订单日志表)
    @Transactional
    public Long saveOrder(OrderForm orderForm) {
        Long userId = SecurityContextHolder.getUserId();
        String userName = SecurityContextHolder.getUserName();
        OrderInfo orderInfo = new OrderInfo();
        orderInfo.setUserId(userId);
        orderInfo.setNickName(userName);
        orderInfo.setOrderNo(orderForm.getTradeNo());

        List<OrderItem> orderItemList = orderForm.getOrderItemList();
        BigDecimal totalAmount = new BigDecimal(0);
        for (OrderItem orderItem : orderItemList) {
            totalAmount = totalAmount.add(orderItem.getSkuPrice().multiply(new BigDecimal(orderItem.getSkuNum())));
        }
        orderInfo.setTotalAmount(totalAmount);
        orderInfo.setOriginalTotalAmount(totalAmount);
        orderInfo.setFeightFee(new BigDecimal(0));
        orderInfo.setOrderStatus(0);

        R<UserAddress> userAddressResult = remoteUserAddressService.getUserAddress(userId, SecurityConstants.INNER);
        if (R.FAIL == userAddressResult.getCode()){
            throw new ServiceException(userAddressResult.getMsg());
        }
        UserAddress userAddress = userAddressResult.getData();
        orderInfo.setReceiverName(userAddress.getName());
        orderInfo.setReceiverPhone(userAddress.getPhone());
        orderInfo.setReceiverTagName(userAddress.getTagName());
        orderInfo.setReceiverProvince(userAddress.getProvinceCode());
        orderInfo.setReceiverCity(userAddress.getCityCode());
        orderInfo.setReceiverDistrict(userAddress.getDistrictCode());
        orderInfo.setReceiverAddress(userAddress.getFullAddress());
        orderInfo.setCreateBy(userName);

        orderInfoMapper.insert(orderInfo);

        Long orderId = orderInfo.getId();
        for (OrderItem orderItem : orderItemList) {
            orderItem.setOrderId(orderId);
            orderItemMapper.insert(orderItem);
        }

        OrderLog orderLog = new OrderLog();
        orderLog.setOrderId(orderId);
        orderLog.setOperateUser("用户");
        orderLog.setProcessStatus(0);
        orderLog.setNote("提交订单");
        orderLogMapper.insert(orderLog);

        return orderId;
    }

    /**
     * 即刻购买
     * @param skuId skuid
     * @return TradeVo
     */
    @Override
    public TradeVo buy(Long skuId) {
        Long userId = SecurityContextHolder.getUserId();

        //准备List<OrderItem>
        R<ProductSku> productSkuResult = remoteProductService.getProductSku(skuId, SecurityConstants.INNER);
        if (R.FAIL == productSkuResult.getCode()){
            throw new ServiceException(productSkuResult.getMsg());
        }
        ProductSku productSku = productSkuResult.getData();
        ArrayList<OrderItem> orderItemList = new ArrayList<>();
        OrderItem orderItem = new OrderItem();
        orderItem.setSkuId(productSku.getId());
        orderItem.setSkuName(productSku.getSkuName());
        orderItem.setThumbImg(productSku.getThumbImg());
        orderItem.setSkuPrice(productSku.getSalePrice());
        orderItem.setSkuNum(1);
        orderItemList.add(orderItem);

        //准备商品价格:BigDecimal类型
        BigDecimal totalAmout = orderItem.getSkuPrice();

        //生成交易流水号
        String tradeNo = getTradeNo(userId);

        TradeVo tradeVo = new TradeVo();
        tradeVo.setOrderItemList(orderItemList);
        tradeVo.setTotalAmount(totalAmout);
        tradeVo.setTradeNo(tradeNo);

        return tradeVo;
    }

    /**
     * 获取用户订单分页列表
     * @param orderStatus 订单状态
     * @return 订单分页列表
     */
    @Override
    public List<OrderInfo> selectUserOrderInfoList(Integer orderStatus) {
        Long userId = SecurityContextHolder.getUserId();
        LambdaQueryWrapper<OrderInfo> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(OrderInfo::getUserId,userId);
        if (orderStatus != null){
            queryWrapper.eq(OrderInfo::getOrderStatus,orderStatus);
        }
        queryWrapper.orderByDesc(OrderInfo::getCreateTime);
        List<OrderInfo> orderInfoList = orderInfoMapper.selectList(queryWrapper);
        if (CollectionUtils.isNotEmpty(orderInfoList)){
            List<Long> orderIdList = orderInfoList.stream().map(OrderInfo::getId).toList();
            List<OrderItem> orderItemList = orderItemMapper.selectList(new LambdaQueryWrapper<OrderItem>().in(OrderItem::getOrderId, orderIdList));
            Map<Long, List<OrderItem>> orderIdToOrderItemMap = orderItemList.stream().collect(Collectors.groupingBy(OrderItem::getOrderId));
            for (OrderInfo orderInfo : orderInfoList) {
                orderInfo.setOrderItemList(orderIdToOrderItemMap.get(orderInfo.getId()));
            }
        }
        return orderInfoList;
    }

    /**
     * 超时未支付,系统取消订单
     * @param orderId 用户id
     */
    @Override
    public void processCloseOrder(long orderId) {
        OrderInfo orderInfo = orderInfoMapper.selectById(orderId);
        if (orderInfo != null && orderInfo.getOrderStatus().intValue() == 0){
            orderInfo.setOrderStatus(-1);
            orderInfo.setCancelTime(new Date());
            orderInfo.setCancelReason("超时未支付,系统取消订单");
            orderInfoMapper.updateById(orderInfo);

            //记录日志
            OrderLog orderLog = new OrderLog();
            orderLog.setOrderId(orderInfo.getId());
            orderLog.setProcessStatus(-1);
            orderLog.setOperateUser("系统");
            orderLog.setNote("超时未支付,系统取消订单");
            orderLogMapper.insert(orderLog);

            //发送MQ消息通知商品系统解锁库存
            rabbitService.sendMsg(MqConst.EXCHANGE_PRODUCT, MqConst.ROUTING_UNLOCK, orderInfo.getOrderNo());
        }
    }

    /**
     * 用户取消订单
     * @param orderId 订单id
     */
    @Override
    public void cancelOrder(Long orderId) {
        OrderInfo orderInfo = orderInfoMapper.selectById(orderId);
        if (orderInfo != null && orderInfo.getOrderStatus().intValue() == 0){
            orderInfo.setOrderStatus(-1);
            orderInfo.setCancelTime(new Date());
            orderInfo.setCancelReason("用户取消订单");
            orderInfoMapper.updateById(orderInfo);

            //记录日志
            OrderLog orderLog = new OrderLog();
            orderLog.setOrderId(orderInfo.getId());
            orderLog.setProcessStatus(-1);
            orderLog.setOperateUser("用户");
            orderLog.setNote("用户取消订单");
            orderLogMapper.insert(orderLog);

            //发送MQ消息通知商品系统解锁库存
            rabbitService.sendMsg(MqConst.EXCHANGE_PRODUCT, MqConst.ROUTING_UNLOCK, orderInfo.getOrderNo());
        }
    }

    /**
     * 根据订单号获取订单信息
     * @param orderNo 订单号
     * @return 订单信息
     */
    @Override
    public OrderInfo getByOrderNo(String orderNo) {
        OrderInfo orderInfo = orderInfoMapper.selectOne(new LambdaQueryWrapper<OrderInfo>()
                .eq(OrderInfo::getOrderNo, orderNo));
        List<OrderItem> orderItemList = orderItemMapper.selectList(new LambdaQueryWrapper<OrderItem>()
                .eq(OrderItem::getOrderId, orderInfo.getId()));
        orderInfo.setOrderItemList(orderItemList);

        return orderInfo;
    }

    /**
     * 监听订单支付成功消息：更新订单状态；扣减商品库存
     * @param orderNo 订单号
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void processPaySucess(String orderNo) {
        //获取订单信息
        OrderInfo orderInfo = orderInfoMapper.selectOne(new LambdaQueryWrapper<OrderInfo>().eq(OrderInfo::getOrderNo, orderNo).select(OrderInfo::getId, OrderInfo::getOrderStatus));
        //未支付
        if(orderInfo.getOrderStatus().intValue() == 0) {
            orderInfo.setOrderStatus(1);
            orderInfo.setPaymentTime(new Date());
            orderInfoMapper.updateById(orderInfo);
        }
    }
}
